<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
//use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Capsule\Manager;
use Session;
use DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Log;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\UserRole;
use App\User;
use App\Roles;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function index(Request $request) {
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);

		// 列表
		$users = new User;
		$userObj = $users->getUsersList();
		$data['users'] = $userObj;

		return view('user.list')->with($data);
	}

	public function create(Request $request)
	{
		// 获取权限列表
		$data['roles'] = Roles::where('is_del',1)->get();
		return view('user.create')->with($data);
	}

	public function checkNameExist(Request $request){
		$account = $request->name;
		if(!$account){
			return '-1';
		}
		$userObj = User::where('name',$account)->get();
		if(count($userObj) >=1){
			return 1;// 存在
		}
	}


	public function store(CreateUserRequest $request){
//        Log::info(__FILE__.__LINE__."新增数据保持");
        DB::beginTransaction();
        $users = new User();
        $users->name =$request->name;
        $users->email =$request->email;
        $users->username =$request->username;
        $users->password = bcrypt(trim($request->password));

        if($users->save()){
            if($request->role_id){
                $userRole = new UserRole();
                $userRole->user_id = $users->id;
                $userRole->role_id = $request->role_id;
                $userRole->save();
            }

            DB::commit();


	        $adminUser = Auth::user();
	        if($adminUser){
		        $userId = $adminUser->id;
		        $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').' 新增了【  '.$request->name.' 】管理员';
		        adminOperationLog($request,$userId,$logs);
	        }

            return redirect('user/list')->with('success','新增成功');
        }else{
            DB::rollback();
            return redirect()->back()->withInput();
        }
//        return back()->withErrors('form errors');
//        $request->session()->flash("emEts", trans('message.emailHasRegistered'));
//        return Redirect::back()->withInput();
//        return Redirect::back()->withInput()->withErrors(['fail' => trans('message.updateLeadFail')]);
}


	public function edit($id)
	{
		$users = new User;
		$userInfo = $users->get_user_one($id);
		$data['userInfo'] = $userInfo;
		$data['roles'] = Roles::where('is_del',1)->get();

		return view('user.edit')->with($data);

	}


    public function update(UpdateUserRequest $request, $id){

        DB::beginTransaction();
        $users = User::find($id);
        $users->name =$request->name;
        $users->email =$request->email;
        $users->username =$request->username;
        if($request->password){
            $users->password =bcrypt(trim($request->password));
        }

        $user_id =$request->user_id;
//        $users->password = bcrypt(hash("sha512", trim($request->password)));

        if(!$users->save()){
            DB::rollback();
            return Redirect::back()->withInput()->withErrors(['fail' => trans('message.updateFail')]);
        }

        if($role_id =$request->role_id){
            $userR = UserRole::getUserRole($user_id);
//            dd($userR);
            if(!$userR){
                $userRole = new UserRole();
                $userRole->user_id = $user_id;
                $userRole->role_id = $role_id;
                $userRole->save();
            }else{
                DB::table('admin_role_users')
                ->where('user_id',$user_id)
                ->update(array(
                    'role_id' => $role_id,
                ));
            }
        }

        DB::commit();


	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'编辑了【 '.$request->name.' 】管理员';
		    adminOperationLog($request,$userId,$logs);
	    }

        return Redirect::to(url('user/list'))->with('success', trans('message.updateSuccess'));

    }

	public function deleteUser(Request $request)
	{
		$uid = $request->id;
	    if(!$uid){
            return '-1';
        }

		$userName = User::getNameById($uid);

        DB::beginTransaction();

        //  del
        $affectId = User::where('id',$uid)->delete();
        if(!$affectId){
            DB::rollback();
            return -1;
        }

        if(UserRole::getUserRole($uid)){
            UserRole::where('user_id',$uid)->delete();
        }

        DB::commit();


		$adminUser = Auth::user();
		if($adminUser){
			$userId = $adminUser->id;
			$logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'删除了【 '.$userName.' 】管理员';
			adminOperationLog($request,$userId,$logs);
		}
        return 1;

//		if ($this->form()->destroy($id)) {
//			return response()->json(['msg' => 'delete success!']);
//		}

	}


}





